// 'use client'
import { Toast } from 'antd-mobile'
import { signOut} from "next-auth/react";

type JSONValue = string | number | boolean | { [x: string]: JSONValue } | Array<JSONValue>;

type GetConfig = Omit<RequestInit, 'method' | 'body'> & {
  _autoLoading?: boolean
};
type PostConfig = Omit<RequestInit, 'method'> & {
  _autoLoading?: boolean
};
type ExtendedRequestInit = RequestInit & {
  headers?: HeadersInit & { _autoLoading?: boolean };
};
class Http {
  // baseURL: string;

  // constructor(baseURL: string) {
  //   this.baseURL = baseURL;
  // }

  async request<R = unknown>(url: string, config: ExtendedRequestInit): Promise<R> {
    // // 添加 JWT
    // const jwt = typeof window !== 'undefined' ? localStorage.getItem('jwt') : null;
    // if (jwt) {
    //   config.headers = { ...config.headers, 'Authorization': `Bearer ${jwt}` };
    // }

    // 显示加载提示
    if (config.headers && config.headers['_autoLoading'] === true) {
      // 显示加载中...
    }

    try {
      const response = await fetch(`/api${url}`, config);

      // 隐藏加载提示
      if (config.headers && config.headers['_autoLoading'] === true) {
        // 隐藏提示
      }

      if (!response.ok) {
        const errorData = await response.json();
        this.handleError(response.status, errorData, config);
        throw new Error(errorData || 'Unknown Error');
      }
      return await response.json();
    } catch (error) {
      throw error;
    }
  }

  private handleError(status: number, data: any, config: ExtendedRequestInit) {
    switch (status) {
      case 400:
        // 显示错误提示
        Toast.show({ icon: 'fail', content: `参数错误：${data}` })
        break;
      case 401:
        // 跳转到登录
        Toast.show({ icon: 'fail', content: '登录过期，请重新登录' })
        const {pathname,search} = window.location
        // const url = `${window.location.origin}/login?return_to=${pathname}${search}`

        setTimeout(() => {
          signOut({
            callbackUrl: `/login?return_to=${pathname}${search}`,
          })
        }, 1500)
        break;
      case 403:
        // 跳转到登录
        Toast.show({ icon: 'fail', content: data || '服务器拒绝访问' })
        break;
      case 404:
      //   // 跳转到登录
        Toast.show({ icon: 'fail', content: '请求地址错误', })
        break;
      case 429:
        // 显示请求太频繁提示
        Toast.show({ icon: 'fail', content: '请求太频繁了' })
        break;
      case 500:
        Toast.show({ icon: 'fail', content: data || '服务器故障'})
        break;
      default:
        Toast.show({ icon: 'fail', content: '未知错误'})
        break;
    }
  }

  get<R = unknown>(url: string, query?: Record<string, JSONValue>, config?: GetConfig) {
    const queryString = query ? `?${new URLSearchParams(query as any).toString()}` : '';
    return this.request<R>(`${url}${queryString}`, { ...config, method: 'GET' });
  }

  post<R = unknown>(url: string, data?: Record<string, JSONValue>, config?: PostConfig) {
    return this.request<R>(url, { ...config, method: 'POST', body: JSON.stringify(data) });
  }

  patch<R = unknown>(url: string, data?: Record<string, JSONValue>, config?: PostConfig) {
    return this.request<R>(url, { ...config, method: 'PATCH', body: JSON.stringify(data) });
  }

  delete<R = unknown>(url: string, query?: Record<string, JSONValue>, config?: GetConfig) {
    const queryString = query ? `?${new URLSearchParams(query as any).toString()}` : '';
    return this.request<R>(`${url}${queryString}`, { ...config, method: 'DELETE' });
  }
}

export const cFetch = new Http();
